from qiniu import Auth, put_file, etag
from flask import current_app
import os


class QiniuTool:
    q = None

    def __init__(self):
        ak = current_app.config["QINIU_AK"]
        sk = current_app.config["QINIU_SK"]
        self.q = Auth(ak, sk)

    def upload_file(self, localfile, new_file):
        # 要上传的空间
        bucket_name = 'xiaocaicai1'
        # 上传后保存的文件名
        key = new_file
        # 生成上传 Token，可以指定过期时间等
        token = self.q.upload_token(bucket_name, key, 3600)
        # 要上传文件的本地路径
        # localfile

        ret, info = put_file(token, key, localfile, version='v2')
        assert ret['key'] == key
        assert ret['hash'] == etag(localfile)

        return ret["key"]


if __name__ == '__main__':
    from app import app

    with app.app_context():
        qn = QiniuTool()
        file_path = os.path.join(
            os.path.abspath("./../"),
            "static/1.jpg"
        )
        filename = qn.upload_file(file_path, "00000000.jpg")
        print(filename)
